﻿using System.Windows;
using DenisVuyka.Controls.PropertyGrid.Metadata;
using DenisVuyka.Controls.PropertyGrid.Resources;
using Microsoft.Win32;
using Microsoft.Windows.Design.PropertyEditing;

namespace DenisVuyka.Controls.PropertyGrid.ValueEditors
{
  public class FileBrowserDialogPropertyValueEditor : DialogPropertyValueEditor
  {
    private EditorResources resources = new EditorResources();

    public FileBrowserDialogPropertyValueEditor()
    {
      this.InlineEditorTemplate = resources.FileBrowserInlineEditorTemplate;
    }
        
    public override void ShowDialog(PropertyValue propertyValue, IInputElement commandSource)
    {
      if (propertyValue == null) return;
      if (propertyValue.ParentProperty.IsReadOnly) return;

      OpenFileDialog ofd = new OpenFileDialog();
      ofd.Multiselect = false;

      PropertyItem property = propertyValue.ParentProperty as PropertyItem;
      if (property != null)
      {
        OpenFileDialogOptionsAttribute optionsAttribute = (OpenFileDialogOptionsAttribute)property.Attributes[typeof(OpenFileDialogOptionsAttribute)];        
        if (optionsAttribute != null)
          optionsAttribute.ConfigureDialog(ofd);
      }

      if (ofd.ShowDialog() == true)
        propertyValue.StringValue = ofd.FileName;
    }
  }
}
